package com.blb.demo;

/**
 * 等待和通知机制
 */
public class WaitNotifyDemo {

    public void testWait(){
        synchronized (this){
            System.out.println(Thread.currentThread().getName()+"执行了！！");
            try {
                //当前线程等待
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"结束了！！");
        }
    }

    public void testNotify(){
        synchronized (this) {
            //通知所有等待的子线程
            this.notifyAll();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyDemo demo = new WaitNotifyDemo();
        //启动一个线程执行等待功能
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                demo.testWait();
            }).start();
        }
        //3s主线程通知
        Thread.sleep(3000);
        demo.testNotify();
    }
}
